/*
 * Copyright (C) 2016 huanghaibin_dev <huanghaibin_dev@163.com>
 * WebSite https://github.com/MiracleTimes-Dev
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.talkweb.calendarview;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.TableLayout;
import ohos.app.Context;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * 年份布局选择View
 */
public final class YearRecyclerView extends TableLayout implements Component.EstimateSizeListener {
    private CalendarViewDelegate mDelegate;
    private OnMonthSelectedListener mListener;
    private List<Month> monthList;
    private int itemWidth, itemHeight;

    public YearRecyclerView(Context context) {
        this(context, null);
    }

    public YearRecyclerView(Context context, @Nullable AttrSet attrs) {
        super(context, attrs);
        monthList = new ArrayList<>();
        setColumnCount(3);
        setRowCount(4);
        setEstimateSizeListener(this);
    }


    /**
     * 设置
     *
     * @param delegate delegate
     */
    final void setup(CalendarViewDelegate delegate) {
        this.mDelegate = delegate;
    }

    /**
     * 初始化年视图
     *
     * @param year year
     */
    final void init(int year) {
        java.util.Calendar date = java.util.Calendar.getInstance();
        monthList.clear();
        for (int i = 1; i <= 12; i++) {
            date.set(year, i - 1, 1);
            int mDaysCount = CalendarUtil.getMonthDaysCount(year, i);
            Month month = new Month();
            month.setDiff(CalendarUtil.getMonthViewStartDiff(year, i, mDelegate.getWeekStart()));
            month.setCount(mDaysCount);
            month.setMonth(i);
            month.setYear(year);
            monthList.add(month);
        }
//        notifyAdapterDataSetChanged();
    }

    /**
     * 更新周起始
     */
    final void updateWeekStart() {
        for (Month month : monthList) {
            month.setDiff(CalendarUtil.getMonthViewStartDiff(month.getYear(), month.getMonth(), mDelegate.getWeekStart()));
        }
    }

    /**
     * 更新字体颜色大小
     */
    final void updateStyle() {
        for (int i = 0; i < getChildCount(); i++) {
            YearView view = (YearView) getComponentAt(i);
            view.updateStyle();
            view.invalidate();
        }
    }

    /**
     * 月份选择事件
     *
     * @param listener listener
     */
    final void setOnMonthSelectedListener(OnMonthSelectedListener listener) {
        this.mListener = listener;
    }


    void notifyAdapterDataSetChanged() {
        if (itemWidth * itemHeight == 0) {
            return;
        }
        removeAllComponents();

        for (int i = 0; i < monthList.size(); i++) {
            addItem(monthList.get(i));
        }
    }

    private void addItem(Month month) {
        YearView yearView;
        if (TextUtils.isEmpty(mDelegate.getYearViewClassPath())) {
            yearView = new DefaultYearView(mContext);
        } else {
            try {
                Constructor constructor = mDelegate.getYearViewClass().getConstructor(Context.class);
                yearView = (YearView) constructor.newInstance(mContext);
            } catch (Exception e) {
                e.printStackTrace();
                yearView = new DefaultYearView(mContext);
            }
        }
        yearView.setup(mDelegate);
//        yearView.measureSize(336, 483);
        yearView.measureSize(itemWidth, itemHeight);
        yearView.init(month.getYear(), month.getMonth());
        yearView.setClickedListener(component -> {
            if (mListener != null && mDelegate != null) {
                if (!CalendarUtil.isMonthInRange(month.getYear(), month.getMonth(),
                        mDelegate.getMinYear(), mDelegate.getMinYearMonth(),
                        mDelegate.getMaxYear(), mDelegate.getMaxYearMonth())) {
                    return;
                }
                mListener.onMonthSelected(month.getYear(), month.getMonth());
                if (mDelegate.mYearViewChangeListener != null) {
                    mDelegate.mYearViewChangeListener.onYearViewChange(true);
                }
            }
        });

        LayoutConfig config = new TableLayout.LayoutConfig(
                itemWidth, itemHeight
        );

        addComponent(yearView, config);
    }


    @Override
    public boolean onEstimateSize(int i, int i1) {
        if (itemWidth * itemHeight == 0) {
            int sizew = EstimateSpec.getSize(i);
            int sizeh = EstimateSpec.getSize(i1);
            System.out.println("w=" + sizew + ",h=" + sizeh);
            itemWidth = sizew / 3;
            itemHeight = sizeh / 4;
            notifyAdapterDataSetChanged();
        }

        return false;
    }


    interface OnMonthSelectedListener {
        void onMonthSelected(int year, int month);
    }
}
